package com.google.code.customercare.common;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;

//import sun.misc.BASE64Encoder;

public final class PasswordService {

	private static Logger log = Logger.getLogger(PasswordService.class);
	
	public static void main(String[] args) {
		try {
			System.out.print(encrypt("admin"));
		} catch (NoSuchAlgorithmException e) {
			log.error("Error", e);
		} catch (UnsupportedEncodingException e) {
			log.error("Error", e);
		}
	}

	/**
	 * Return the String representation of the newly generated hash back to our
	 * registration servlet so that it can be stored in the database. The
	 * user.getPassword() method now returns "5yfRRkrhJDbomacm2lsvEdg4GyY="
	 * 
	 * @param plaintext
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	public static String encrypt(String plaintext)
			throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("SHA"); // step 2
		} catch (NoSuchAlgorithmException e) {
			throw e;
		}
		try {
			md.update(plaintext.getBytes("UTF-8")); // step 3
		} catch (UnsupportedEncodingException e) {
			throw e;
		}

		byte raw[] = md.digest(); // step 4
		// String hash = (new BASE64Encoder()).encode(raw); // step 5
		String hash = null;
		return hash; // step 6
	}

}